#include "PSPTime.h"

#include <psptypes.h>
#include <psprtc.h>

namespace GenBen {
	
PSPTime::PSPTime()
{
	perf_frequency = sceRtcGetTickResolution();
	sceRtcGetCurrentTick(&start_time);

	fps_limit = current_time_ms = last_fps_update = fps = 0;

	update();
}

PSPTime::~PSPTime()
{
}

string PSPTime::timeToString(uint time)
{
	char time_str[8];
	sprintf(time_str, "%02u:%02u", time / (1000 * 60), (time / 1000) % 60);
	return string(time_str);
}

void PSPTime::update()
{
	old_time_ms = current_time_ms;

	// Fps is already limited for psp by vsync
	//do
	//{
		sceRtcGetCurrentTick(&current_time);
		current_time_ms = perfCounterToMs(current_time);
		d_time_ms = current_time_ms - old_time_ms;
	//} while(fps_limit != 0 && d_time_ms < (1000 / fps_limit));

	time_scale = (float)d_time_ms / 1000.0f;

	if (last_fps_update + 1000 <= current_time_ms)
	{
		fps = frames_drawn;
		frames_drawn = 0;
		last_fps_update = current_time_ms;
	}

	frames_drawn++;
}

uint PSPTime::perfCounterToMs(uint64 time)
{
	return (uint)((time - start_time) * 1000ULL / perf_frequency);
}

} // namespace
